package org.wdcode.web.socket.client;

import java.util.concurrent.locks.Lock;

import org.wdcode.common.util.CommonUtil;
import org.wdcode.core.concurrent.LockFactory;

/**
 * Socket客户端工厂
 * @author WD
 * @since JDK6
 * @version 1.0 2010-01-26
 */
public final class SocketClientFactory {
	// 同步锁
	private final static Lock		LOCK;
	// Socket客户端
	private static SocketClientTCP	tcp;
	private static SocketClientUDP	udp;

	/**
	 * 静态初始化
	 */
	static {
		LOCK = LockFactory.getLock();
	}

	/**
	 * 返回一个单例的SocketClientTCP
	 * @return SocketClientTCP
	 */
	public final static SocketClientTCP getSocketTCP() {
		// 判断为空
		if (CommonUtil.isEmpty(tcp)) {
			// 锁
			LOCK.lock();
			// 判断为空
			if (CommonUtil.isEmpty(tcp)) {
				tcp = getSocketTCP();
			}
			// 解缩
			LOCK.unlock();
		}
		// 返回Socket客户端
		return tcp;
	}

	/**
	 * 实例化一个新SocketClientTCP对象
	 * @return SocketClientTCP
	 */
	public final static SocketClientTCP newSocketTCP() {
		return new SocketClientTCPImpl();
	}

	/**
	 * 返回一个单例的SocketClientTCP
	 * @return SocketClientTCP
	 */
	public final static SocketClientUDP getSocketUDP() {
		// 判断为空
		if (CommonUtil.isEmpty(udp)) {
			// 锁
			LOCK.lock();
			// 判断为空
			if (CommonUtil.isEmpty(udp)) {
				udp = newSocketUDP();
			}
			// 解缩
			LOCK.unlock();
		}
		// 返回Socket客户端
		return udp;
	}

	/**
	 * 实例化一个新SocketClientTCP对象
	 * @return SocketClientTCP
	 */
	public final static SocketClientUDP newSocketUDP() {
		return new SocketClientUDPImpl();
	}

	/**
	 * 私有构造
	 */
	private SocketClientFactory() {}
}
